package fr.uha.ensisa.kfetmanager.customer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author JC
 */
public class GetCustomers extends HttpServlet {

    @EJB
    private CustomerManagerRemote customerManager;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	List<Customer> list;
	String nicknameFilter = request.getParameter("customerName");

	try {
	    if(nicknameFilter == null)
		list = customerManager.getCustomers();
	    else
		list = customerManager.getCustomers(nicknameFilter);
	}
	catch(Exception e) {
	    response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Erreur lors de la recherche de clients");
	    return;
	}

	Iterator<Customer> it = list.iterator();

	response.setContentType("application/xml;charset=UTF-8");
	PrintWriter out = response.getWriter();
	try {
	    out.println("<customers>");
	    while(it.hasNext()) {
		Customer c = it.next();

		out.println("<customer>");
		out.println("<id>" + c.getId().toString() + "</id>");
		out.println("<firstname>" + c.getFirstName() + "</firstname>");
		out.println("<lastname>" + c.getLastName() + "</lastname>");
		out.println("<nickname>" + c.getNickname() + "</nickname>");
		out.println("<category>" + c.getCategory() + "</category>");
		out.println("<balance>" + String.valueOf(c.getBalance()) + "</balance>");
		out.println("</customer>");
	    }
	    out.println("</customers>");
	}
	finally {
	    out.close();
	}

    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	processRequest(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	processRequest(req, resp);
    }
}
